package com.ruoyi.chat.LongConnection.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.nio.charset.StandardCharsets;

/**
 * @package: com.ruoyi.chat.LongConnection.util
 * @className: LongConnectionMsgUtil
 * @description: 长连接返回信息包装类
 * @author MaTaoxun
 * @date 2021/9/28 22:57
*/
public class LongConnectionMsgUtil {
    public static ObjectMapper mapper = new ObjectMapper();

    /**
    * @author MaTaoxun
    * @date 2021/9/28 22:57
    */
    public static ByteBuf StrToByteBuf(String msg){
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        return ByteBufAllocator.DEFAULT.buffer().writeInt(bytes.length).writeBytes(bytes);
    }

    /**
     * @author MaTaoxun
     * @date 2021/9/28 22:57
     */
    public static ByteBuf bytesToByteBuf(byte[] msg){
        return ByteBufAllocator.DEFAULT.buffer().writeInt(msg.length).writeBytes(msg);
    }


    /**
     * @author MaTaoxun
     * @date 2021/9/28 22:57
     * @return
     */
    public static TextWebSocketFrame ObjectToWSTextResult(Object object) throws JsonProcessingException {
        return new TextWebSocketFrame(mapper.writeValueAsString(object));
    }
}
